<template>
  <div class="user-management page-container">
    <div class="page-header">
      <h2>用户管理</h2>
      <el-button type="primary" :icon="Plus" @click="showAddDialog = true">
        添加用户
      </el-button>
      <el-button type="info" @click="exportUsers">
        导出用户
      </el-button>
      <el-upload
        class="upload-btn"
        :show-file-list="false"
        :before-upload="beforeUpload"
        :on-change="handleImport"
        accept=".csv"
      >
        <el-button type="warning">导入用户</el-button>
      </el-upload>
      <el-button type="info" @click="showImportRules = true">导入规则</el-button>
    </div>

    <el-card>
      <el-table :data="users" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="employee_id" label="工号" width="120" />
        <el-table-column prop="phone" label="电话" width="130" />
        <el-table-column prop="position" label="职位" width="120" />
        <el-table-column prop="department" label="部门" width="120" />
        <el-table-column label="区域" width="150">
          <template #default="scope">
            <span v-if="scope.row.areas && scope.row.areas.length > 0">
              {{ scope.row.areas.join(', ') }}
            </span>
            <span v-else-if="scope.row.area_name">
              {{ scope.row.area_name }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="scope">
            {{ scope.row.gender === 'male' ? '男' : scope.row.gender === 'female' ? '女' : scope.row.gender }}
          </template>
        </el-table-column>
        <el-table-column prop="ethnicity" label="民族" width="100" />
        <el-table-column prop="hire_date" label="入职时间" width="120" />
        <el-table-column prop="role" label="角色" width="100">
          <template #default="scope">
            {{ 
              scope.row.role === 'admin' ? '管理员' : 
              scope.row.role === 'dispatcher' ? '调度员' : 
              scope.row.role === 'worker' ? '维修工' : 
              scope.row.role === 'warehouse_manager' ? '仓库管理员' : 
              scope.row.role 
            }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_driver" label="驾驶员" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.is_driver ? 'success' : 'info'">
              {{ scope.row.is_driver ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 导入规则说明对话框 -->
    <el-dialog
      v-model="showImportRules"
      title="CSV导入规则说明"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="import-rules">
        <h4>CSV文件格式要求：</h4>
        <ol>
          <li><strong>文件编码：</strong>UTF-8编码</li>
          <li><strong>分隔符：</strong>英文逗号(,)</li>
          <li><strong>表头：</strong>第一行必须包含字段名称</li>
        </ol>
        
        <h4>必填字段：</h4>
        <ul>
          <li><strong>用户名：</strong>唯一标识，不能重复</li>
          <li><strong>姓名：</strong>用户真实姓名</li>
          <li><strong>邮箱：</strong>有效邮箱地址，不能重复</li>
          <li><strong>工号：</strong>员工工号，不能重复</li>
          <li><strong>身份证号：</strong>18位身份证号码，不能重复</li>
          <li><strong>性别：</strong>male(男) 或 female(女)</li>
          <li><strong>入职时间：</strong>格式为YYYY-MM-DD</li>
        </ul>
        
        <h4>可选字段：</h4>
        <ul>
          <li><strong>电话：</strong>联系电话</li>
          <li><strong>职位：</strong>工作职位</li>
          <li><strong>部门：</strong>所属部门</li>
          <li><strong>区域：</strong>工作区域，多个区域用竖线(|)分隔，如：区域1|区域2|区域3</li>
          <li><strong>民族：</strong>民族信息</li>
          <li><strong>角色：</strong>admin(管理员)、dispatcher(调度员)、worker(维修工)、warehouse_manager(仓库管理员)，默认为worker</li>
          <li><strong>状态：</strong>active(在职)、inactive(离职)，默认为active</li>
          <li><strong>是否驾驶员：</strong>true(是) 或 false(否)，默认为false</li>
          <li><strong>技能：</strong>多个技能用竖线(|)分隔</li>
          <li><strong>离职时间：</strong>格式为YYYY-MM-DD</li>
          <li><strong>电工证有效期：</strong>格式为YYYY-MM-DD</li>
          <li><strong>登高证有效期：</strong>格式为YYYY-MM-DD</li>
          <li><strong>批号：</strong>批次号码</li>
          <li><strong>备注：</strong>其他备注信息</li>
        </ul>
        
        <h4>注意事项：</h4>
        <ul>
          <li>导入的用户默认密码为：<code>defaultPassword123</code></li>
          <li>身份证号的第17位数字必须与性别匹配（奇数为男，偶数为女）</li>
          <li>如果字段值包含逗号，请用双引号包围该字段</li>
          <li>日期格式必须严格按照YYYY-MM-DD格式</li>
          <li>导入失败的记录会在控制台显示错误信息</li>
        </ul>
      </div>
      <template #footer>
        <el-button @click="showImportRules = false">关闭</el-button>
        <el-button type="primary" @click="downloadTemplate">下载模板</el-button>
      </template>
    </el-dialog>

    <el-dialog
      v-model="showAddDialog"
      :title="editingUser ? '编辑用户' : '添加用户'"
      width="800px"
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="工号" prop="employee_id">
              <el-input v-model="form.employee_id" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="职位" prop="position">
              <el-input v-model="form.position" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="department">
              <el-input v-model="form.department" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="角色" prop="role">
              <el-select v-model="form.role" placeholder="请选择角色" style="width: 100%">
                <el-option label="管理员" value="admin" />
                <el-option label="调度员" value="dispatcher" />
                <el-option label="维修工" value="worker" />
                <el-option label="仓库管理员" value="warehouse_manager" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
                <el-option label="在职" value="active" />
                <el-option label="离职" value="inactive" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="区域（网格）" prop="area">
              <el-select v-model="form.area" multiple placeholder="请选择区域" style="width: 100%" clearable>
                <el-option
                  v-for="area in areaOptions"
                  :key="area.id"
                  :label="area.name"
                  :value="area.name"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="id_card">
              <el-input v-model="form.id_card" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="民族" prop="ethnicity">
              <el-input v-model="form.ethnicity" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
                <el-option label="男" value="male" />
                <el-option label="女" value="female" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入职时间" prop="hire_date">
              <el-date-picker v-model="form.hire_date" type="date" placeholder="请选择入职时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="离职时间">
              <el-date-picker v-model="form.resignation_date" type="date" placeholder="请选择离职时间" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否驾驶员">
              <el-switch v-model="form.is_driver" active-text="是" inactive-text="否" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="电工证有效期">
              <el-date-picker v-model="form.electrician_cert_expiry" type="date" placeholder="请选择电工证有效期" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="登高证有效期">
              <el-date-picker v-model="form.height_cert_expiry" type="date" placeholder="请选择登高证有效期" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批号">
              <el-input v-model="form.batch_number" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="技能" prop="skills">
              <el-select v-model="form.skills" multiple filterable allow-create placeholder="请选择或输入技能" style="width: 100%">
                <el-option
                  v-for="skill in commonSkills"
                  :key="skill"
                  :label="skill"
                  :value="skill"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注">
          <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" autocomplete="new-password" :placeholder="editingUser ? '留空则不修改密码' : '请输入密码'" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { apiClient } from '@/api/axios'
import { areasApi } from '@/api/areas'

const loading = ref(false)
const showAddDialog = ref(false)
const showImportRules = ref(false)
const editingUser = ref<any>(null)
const formRef = ref<any>(null)

const users = ref<any[]>([])
const areaOptions = ref<any[]>([])

const form = reactive({
  username: '',
  name: '',
  email: '',
  employee_id: '',
  phone: '',
  position: '',
  department: '',
  role: 'worker',
  skills: [],
  password: '',
  // 新增必填字段
  area: [],
  id_card: '',
  ethnicity: '',
  gender: '',
  hire_date: '',
  is_driver: false,
  // 新增可选字段
  password_field: '',
  status: 'active',
  resignation_date: '',
  electrician_cert_expiry: '',
  height_cert_expiry: '',
  batch_number: '',
  remarks: ''
})

const commonSkills = ref([
  'JavaScript', 'Python', 'Java', 'C++', 'React', 'Vue.js', 'Node.js',
  '数据库管理', '网络维护', '系统运维', '项目管理', '测试', '设计'
])

// 身份证号唯一性验证
const validateIdCardUnique = async (rule: any, value: string, callback: any) => {
  if (!value) {
    callback()
    return
  }
  
  // 如果是编辑用户且身份证号未改变，跳过验证
  if (editingUser.value && editingUser.value.id_card === value) {
    callback()
    return
  }
  
  // 检查当前用户列表中是否已存在该身份证号
  const existingUser = users.value.find(user => 
    user.id_card === value && user.id !== editingUser.value?.id
  )
  
  if (existingUser) {
    callback(new Error('该身份证号已存在'))
  } else {
    callback()
  }
}

// 身份证号与性别对应关系验证
const validateIdCardGender = (rule: any, value: string, callback: any) => {
  // 根据验证的字段确定身份证号和性别值
  const idCard = rule.field === 'id_card' ? value : form.id_card
  const gender = rule.field === 'gender' ? value : form.gender
  
  if (!idCard || !gender) {
    callback()
    return
  }
  
  // 身份证号第17位数字，奇数为男性，偶数为女性
  const genderDigit = parseInt(idCard.charAt(16))
  const isIdCardMale = genderDigit % 2 === 1
  const isFormMale = gender === 'male'
  
  if (isIdCardMale !== isFormMale) {
    const expectedGender = isIdCardMale ? '男' : '女'
    callback(new Error(`根据身份证号，性别应为${expectedGender}`))
  } else {
    callback()
  }
}

const rules = computed(() => ({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  employee_id: [{ required: true, message: '请输入工号', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入电话', trigger: 'blur' }],
  position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
  department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  area: [{ required: true, message: '请选择区域（网格）', trigger: 'change' }],
  id_card: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号', trigger: 'blur' },
    { validator: validateIdCardUnique, trigger: 'blur' },
    { validator: validateIdCardGender, trigger: 'blur' }
  ],
  ethnicity: [{ required: true, message: '请输入民族', trigger: 'blur' }],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' },
    { validator: validateIdCardGender, trigger: 'change' }
  ],
  hire_date: [{ required: true, message: '请选择入职时间', trigger: 'change' }],
  password: editingUser.value ? [] : [{ required: true, message: '请输入密码', trigger: 'blur' }]
}))

const loadUsers = async () => {
  loading.value = true
  try {
    const response = await apiClient.get('/users', { params: { page: 1, per_page: 100 } })
    users.value = response.data.users || []
  } catch (error: any) {
    ElMessage.error('加载用户数据失败: ' + (error.message || error))
  } finally {
    loading.value = false
  }
}

const loadAreaOptions = async () => {
  try {
    const response = await areasApi.getAreaOptions()
    console.log('区域选项API响应:', response.data)
    
    // 检查响应数据是否为数组
    if (!Array.isArray(response.data)) {
      console.error('区域选项API返回的数据不是数组:', response.data)
      ElMessage.error('区域数据格式错误')
      areaOptions.value = []
      return
    }
    
    // 后端返回的是直接的数组格式 [{value: id, label: name}]
    // 需要转换为前端期望的格式 [{id: id, name: name}]
    areaOptions.value = response.data.map((area: any) => ({
      id: area.value,
      name: area.label
    }))
  } catch (error: any) {
    console.error('加载区域选项失败:', error)
    console.error('错误详情:', error.response?.data)
    ElMessage.error(`加载区域数据失败: ${error.response?.data?.error || error.message}`)
    areaOptions.value = []
  }
}

const editUser = (user: any) => {
  editingUser.value = user
  Object.assign(form, {
    username: user.username,
    name: user.name || '',
    email: user.email,
    employee_id: user.employee_id || '',
    phone: user.phone || '',
    position: user.position || '',
    department: user.department || '',
    role: user.role,
    skills: user.skills || [],
    password: '',
    // 加载新增字段数据
    area: user.areas || (user.area_name ? [user.area_name] : []),
    id_card: user.id_card || '',
    ethnicity: user.ethnicity || '',
    gender: user.gender || '',
    hire_date: user.hire_date || '',
    is_driver: user.is_driver || false,
    password_field: user.password_field || '',
    status: user.status || 'active',
    resignation_date: user.resignation_date || '',
    electrician_cert_expiry: user.electrician_cert_expiry || '',
    height_cert_expiry: user.height_cert_expiry || '',
    batch_number: user.batch_number || '',
    remarks: user.remarks || ''
  })
  showAddDialog.value = true
}

const deleteUser = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个用户吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await apiClient.delete(`/users/${id}`)
    ElMessage.success('删除成功')
    await loadUsers()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    // 格式化日期字段
    const formatDate = (date: any) => {
      if (!date) return null
      if (date instanceof Date) {
        return date.toISOString().split('T')[0] // 转换为YYYY-MM-DD格式
      }
      return date
    }

    if (editingUser.value) {
      // 编辑用户时提交所有字段
      const updateData: any = {
        username: form.username,
        name: form.name,
        email: form.email,
        employee_id: form.employee_id,
        phone: form.phone,
        position: form.position,
        department: form.department,
        role: form.role,
        skills: form.skills,
        area: form.area,
        id_card: form.id_card,
        ethnicity: form.ethnicity,
        gender: form.gender,
        hire_date: formatDate(form.hire_date),
        is_driver: form.is_driver,
        password_field: form.password_field,
        status: form.status,
        resignation_date: formatDate(form.resignation_date),
        electrician_cert_expiry: formatDate(form.electrician_cert_expiry),
        height_cert_expiry: formatDate(form.height_cert_expiry),
        batch_number: form.batch_number,
        remarks: form.remarks
      }
      if (form.password && form.password.trim() !== '') {
        updateData.password = form.password
      }
      await apiClient.put(`/users/${editingUser.value.id}`, updateData)
      ElMessage.success('更新成功')
    } else {
      // 新增用户时需要密码，格式化日期字段
      const submitData = {
        ...form,
        hire_date: formatDate(form.hire_date),
        resignation_date: formatDate(form.resignation_date),
        electrician_cert_expiry: formatDate(form.electrician_cert_expiry),
        height_cert_expiry: formatDate(form.height_cert_expiry)
      }
      await apiClient.post('/users', submitData)
      ElMessage.success('添加成功')
    }

    showAddDialog.value = false
    resetForm()
    await loadUsers()
  } catch (error: any) {
    ElMessage.error(error.response?.data?.error || error.message || '操作失败')
  }
}

const resetForm = () => {
  editingUser.value = null
  Object.assign(form, {
    username: '',
    name: '',
    email: '',
    employee_id: '',
    phone: '',
    position: '',
    department: '',
    role: 'user',
    skills: [],
    password: '',
    // 重置新增字段
    area: [],
    id_card: '',
    ethnicity: '',
    gender: '',
    hire_date: '',
    is_driver: false,
    password_field: '',
    status: 'active',
    resignation_date: '',
    electrician_cert_expiry: '',
    height_cert_expiry: '',
    batch_number: '',
    remarks: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

onMounted(() => {
  loadUsers()
  loadAreaOptions()
})

// 导出用户数据为CSV文件
const exportUsers = () => {
  if (users.value.length === 0) {
    ElMessage.warning("没有可导出的用户数据")
    return
  }
  const headers = [
    "用户名", "姓名", "邮箱", "工号", "电话", "职位", "部门", "区域", "身份证号", "民族", "性别", 
    "入职时间", "角色", "状态", "是否驾驶员", "技能", "离职时间", "电工证有效期", "登高证有效期", "批号", "备注"
  ]
  const csvRows = []
  csvRows.push(headers.join(","))
  users.value.forEach(user => {
    const row = [
      user.username || "",
      user.name || "",
      user.email || "",
      user.employee_id || "",
      user.phone || "",
      user.position || "",
      user.department || "",
      (user.areas && user.areas.length > 0) ? user.areas.join('|') : (user.area_name || ""),
      user.id_card || "",
      user.ethnicity || "",
      user.gender || "",
      user.hire_date || "",
      user.role || "user",
      user.status || "active",
      user.is_driver ? "true" : "false",
      (user.skills || []).join("|"),
      user.resignation_date || "",
      user.electrician_cert_expiry || "",
      user.height_cert_expiry || "",
      user.batch_number || "",
      user.remarks || ""
    ]
    // 转义逗号和双引号
    const escapedRow = row.map(field => {
      if (typeof field === "string" && (field.includes(",") || field.includes('"'))) {
        return `"${field.replace(/"/g, '""')}"`
      }
      return field
    })
    csvRows.push(escapedRow.join(","))
  })
  const csvString = "\uFEFF" + csvRows.join("\n") // 添加BOM以支持中文
  const blob = new Blob([csvString], { type: "text/csv;charset=utf-8;" })
  const url = URL.createObjectURL(blob)
  const a = document.createElement("a")
  a.href = url
  a.download = "users_export.csv"
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success("导出成功")
}

// 导入前阻止自动上传
const beforeUpload = () => {
  return false
}

// 处理导入的CSV文件
const handleImport = (file: any) => {
  const reader = new FileReader()
  reader.onload = async (e: any) => {
    try {
      const csvText = e.target.result
      const lines = csvText.split('\n').filter((line: string) => line.trim())
      if (lines.length < 2) {
        ElMessage.error("CSV文件格式错误，至少需要表头和一行数据")
        return
      }
      
      const headers = lines[0].split(',').map((h: string) => h.trim().replace(/^"|"$/g, ''))
      const importedUsers = []
      
      for (let i = 1; i < lines.length; i++) {
        const values = parseCSVLine(lines[i])
        if (values.length !== headers.length) {
          console.warn(`第${i + 1}行数据列数不匹配，跳过`)
          continue
        }
        
        const user: any = {}
        headers.forEach((header, index) => {
          const value = values[index]?.trim()
          switch (header) {
            case '用户名':
              user.username = value
              break
            case '姓名':
              user.name = value
              break
            case '邮箱':
              user.email = value
              break
            case '工号':
              user.employee_id = value
              break
            case '电话':
              user.phone = value
              break
            case '职位':
              user.position = value
              break
            case '部门':
              user.department = value
              break
            case '区域':
              // 支持多区域导入，用竖线(|)分隔
              if (value && value.includes('|')) {
                user.area = value.split('|').map(a => a.trim()).filter(a => a)
              } else {
                user.area = value ? [value] : []
              }
              break
            case '身份证号':
              user.id_card = value
              break
            case '民族':
              user.ethnicity = value
              break
            case '性别':
              user.gender = value
              break
            case '入职时间':
              user.hire_date = value
              break
            case '角色':
              user.role = value || 'worker'
              break
            case '状态':
              user.status = value || 'active'
              break
            case '是否驾驶员':
              user.is_driver = value === 'true'
              break
            case '技能':
              user.skills = value ? value.split('|') : []
              break
            case '离职时间':
              user.resignation_date = value
              break
            case '电工证有效期':
              user.electrician_cert_expiry = value
              break
            case '登高证有效期':
              user.height_cert_expiry = value
              break
            case '批号':
              user.batch_number = value
              break
            case '备注':
              user.remarks = value
              break
          }
        })
        
        if (user.username && user.name && user.email && user.employee_id && user.id_card && user.gender && user.hire_date) {
          importedUsers.push(user)
        } else {
          console.warn(`第${i + 1}行缺少必填字段，跳过:`, user)
        }
      }
      
      let successCount = 0
      let failCount = 0
      
      for (const user of importedUsers) {
        try {
          await apiClient.post('/users', {
            ...user,
            password: 'defaultPassword123' // 导入用户默认密码
          })
          successCount++
        } catch (err: any) {
          failCount++
          console.error('导入用户失败:', user.username, err.response?.data?.error || err.message)
        }
      }
      
      ElMessage.success(`导入完成！成功：${successCount}条，失败：${failCount}条`)
      await loadUsers()
    } catch (error) {
      ElMessage.error("CSV文件解析失败，请检查文件格式")
      console.error('CSV解析错误:', error)
    }
  }
  reader.readAsText(file.raw, 'UTF-8')
}

// 解析CSV行，处理逗号和引号
const parseCSVLine = (line: string): string[] => {
  const result = []
  let current = ''
  let inQuotes = false
  
  for (let i = 0; i < line.length; i++) {
    const char = line[i]
    
    if (char === '"') {
      if (inQuotes && line[i + 1] === '"') {
        current += '"'
        i++ // 跳过下一个引号
      } else {
        inQuotes = !inQuotes
      }
    } else if (char === ',' && !inQuotes) {
      result.push(current)
      current = ''
    } else {
      current += char
    }
  }
  
  result.push(current)
  return result
}

// 下载CSV模板
const downloadTemplate = () => {
  const headers = [
    "用户名", "姓名", "邮箱", "工号", "电话", "职位", "部门", "区域", "身份证号", "民族", "性别", 
    "入职时间", "角色", "状态", "是否驾驶员", "技能", "离职时间", "电工证有效期", "登高证有效期", "批号", "备注"
  ]
  const sampleData = [
    "zhangsan", "张三", "zhangsan@example.com", "EMP001", "13800138000", "工程师", "技术部", "A区", 
    "110101199001011234", "汉族", "male", "2024-01-01", "worker", "active", "false", "编程|测试", 
    "", "", "", "BATCH001", "示例用户"
  ]
  
  const csvContent = "\uFEFF" + headers.join(",") + "\n" + sampleData.join(",")
  const blob = new Blob([csvContent], { type: "text/csv;charset=utf-8;" })
  const url = URL.createObjectURL(blob)
  const a = document.createElement("a")
  a.href = url
  a.download = "user_import_template.csv"
  a.click()
  URL.revokeObjectURL(url)
  ElMessage.success("模板下载成功")
}

</script>

<style scoped>
.user-management {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.import-rules {
  line-height: 1.6;
}

.import-rules h4 {
  color: #409eff;
  margin-top: 20px;
  margin-bottom: 10px;
}

.import-rules ol,
.import-rules ul {
  padding-left: 20px;
}

.import-rules li {
  margin-bottom: 8px;
}

.import-rules code {
  background-color: #f5f5f5;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  color: #e74c3c;
}

.import-rules strong {
  color: #2c3e50;
}
</style>